<?php
/**
 * Celebrio Core
 * 
 * @copyright  Copyright (c) 2011 Celebrio Software
 * @package    Celebrio
 * @subpackage Core
 */
namespace Celebrio\Core;

use Celebrio\Modules;

use Nette\Object;
use Albireo\Mode;

use Celebrio\Core\Manifest;
use Celebrio\Core\CriticalException;
use Celebrio\Core\ServiceProvider;
use Celebrio\Diagnostics\Timer;
use Celebrio\Diagnostics\TimerLevel;

/**
 * Description of ModuleLoader
 *
 * @author pavel
 */
class ModuleLoader extends Object {
    const DEPENDENCIES = "dependencies";

    public function loadInstalled() {
        Timer::start("getting all manifests",TimerLevel::DETAILED);
        $manifestLoader = new ManifestLoader();
        $manifests = $manifestLoader->getAllManifests();
        Timer::stop("getting all manifests");
        try {
        	Timer::start("module loader foreach",TimerLevel::DETAILED);
            foreach ($manifests as $manifest) {
                if ($manifest->isInstalled()) {
                    $this->init($manifest); // may throw CriticalException
                    ServiceProvider::registerService($manifest);
                } else {
                    // not installed yet
                }
            }
            Timer::stop("module loader foreach");
            Timer::start("checking critical features",TimerLevel::DETAILED);
            CriticalFeatures::check();
            Timer::stop("checking critical features");
        } catch (CriticalException $e) {
            Mode::setCriticalMode($e->getMessage());
        }
        //$service = ServiceProvider::getAllServices(Modules::FS_DRIVERS);
        //\Nette\Debug::dump($service);
        //throw new \Exception();
    }
    
    private function init(Manifest $manifest) {
        $configuration = Config::current()->loadConfigArray($manifest->getFullNameDots());
        $initClass = $manifest->getInit();
        
        if ($initClass !== null) {
            $initClass->init($configuration);
        } else {
            //\Nette\Debug::dump("No initializing routine found for " . $manifest->getFullNameDots());
        }
    }

}

